package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.common.common.SQLObjectDoing;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.dto.SettlementRecordDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by DK on 16/11/9.
 */
@Repository
public class SettlementRecordRepositoryImpl implements SettlementRecordRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(SettlementRecordRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public SettlementRecordDto findByProductIdAndMerchantIdAndMallId(Long productId, Long merchantId, Long mallId) {
        SQLObjectDoing<SettlementRecordDto> doing = (sql, fields, params, map) -> {
            sql.append("select %s from settlement_record sr where 1=1");
            sql.append(" and sr.product_id = :productId");
            sql.append(" and sr.merchant_id = :merchantId");
            sql.append(" and sr.mall_id = :mallId");
            sql.append(" and sr.is_delete = :isDelete");
            params.put("mallId", mallId);
            params.put("productId", productId);
            params.put("merchantId", merchantId);
            params.put("isDelete", Whether.NO.toString());
            fields.append("sum(sr.settle_num) settleNum, sum(sr.settle_amount) settleAmount, sum(sr.resell_fee) resellFee, sum(sr.sharer_fee) sharerFee, sum(sr.buyer_fee) buyerFee, sum(sr.serve_fee) serveFee");
        };
        return doing.go(SettlementRecordDto.class, jdbcTemplate, log, objectMapper);
    }

    @Override
    public List<SettlementRecordDto> findByFundFlowIdAndMerchantIdAndMallId(Long fundFlowId, Long merchantId, Long mallId) {
        SQLListDoing<SettlementRecordDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s from settlement_record sr where 1=1 ");
            sql.append(" and sr.merchant_id = :merchantId");
            sql.append(" and sr.mall_id = :mallId");
            sql.append(" and sr.fund_flow_id = :fundFlowId");
            params.put("mallId", mallId);
            params.put("merchantId", merchantId);
            params.put("fundFlowId", fundFlowId);
            fields.append("sr.*");
        };
        return doing.go(SettlementRecordDto.class, jdbcTemplate, log, objectMapper);
    }
}
